import React,{useEffect,useState} from 'react'
import {DeleteOutlined,EditOutlined}from '@ant-design/icons'
import http from '../../api'
import {Space,Tag,Table,Popconfirm,Popover,Switch,Button}from 'antd'
import{arrayToTree}from'../../utils/formatSiderData'

export default function Perm() {
  const [permList,setPermList]=useState([])
  //更新单行数据权限
  const onChange=(e,record)=>{
    const id=record.id
    const pagepermisson=e?{pagepermisson:''}:{pagepermisson:1}
    const api=record.grade==1?http.patch('/rights/'+id,pagepermisson)
    :http.patch('/children/'+id,pagepermisson)
    api.then(res=>{
      getTableList()
    })
  }
  //表格配置项
  const column=[
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '权限名称',
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '权限路径',
      key: 'action',
      render: (_, record) => (
        <Tag color={'orange'} key={record.key}>
        {record.key}
      </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm title="确定要删除么？" okText="确认" cancelText="取消" onConfirm={()=>onConfirmDel(record)}>
          <DeleteOutlined style={{color:'red',marginRight:'10px'}} />
             </Popconfirm>
          <Popover content={<Switch defaultChecked onChange={(e)=>onChange(e,record)} />} title="配置项目">
             <Button disabled={record.pagepermisson!=1} type="primary" shape="circle" icon={<EditOutlined />} />
          </Popover>
        </Space>
      ),
    },
  ]

  useEffect(()=>{
    getTableList()
  },[])

  //删除单行数据
  const onConfirmDel=(record)=>{
    const id=record.id
    const api=record.grade==1?http.delete('/rights/'+id)
    :http.delete('/children/'+id)
    api.then(res=>{
      console.log(res);
      getTableList()
    })
  }
   //获取权限列表数据
  const getTableList=()=>{
    const getRootMenu=http.get('/rights')
    const getChildMenu=http.get('/children')
    Promise.all([getRootMenu,getChildMenu]).then(res=>{
      setPermList(arrayToTree(res[0].data,res[1].data))
    })
  }
  return (
    <div>
     <Table columns={column} dataSource={permList} pagination={{ pageSize:5 }}/>;
    </div>
  )
}
